﻿namespace Manhua2.Common
{
    using Manhua2.DataModel;
    using Manhua2.Helper;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Windows.Networking.BackgroundTransfer;
    using Windows.Storage;

    public class CoverCacheManager
    {
        private static object _lockPoint = new object();
        private static List<DownloadOperation> actives = new List<DownloadOperation>();

        public async static Task DownloadCoverAsync(ComicItem comic)
        {
            try
            {
                if (actives.Where(k => k.Progress.Status == BackgroundTransferStatus.Running &&
                                       k.RequestedUri.AbsoluteUri == comic.Comic.CoverUrl).Count() > 0)
                    return;

                string filename = "cover\\" + comic.Comic.Id;
                string appx = "ms-appdata:///local/cover/" + comic.Comic.Id;

                if (await MethodHelper.FileIsExists(filename))
                {
                    comic.Cover = appx;
                    return;
                }

                var downloader = new BackgroundDownloader();
                var file = await ApplicationData.Current.LocalFolder.CreateFileAsync(
                    filename,
                    CreationCollisionOption.ReplaceExisting);

                var download = downloader.CreateDownload(new Uri(comic.Comic.CoverUrl), file);
                download.CostPolicy = BackgroundTransferCostPolicy.Always;
                await HandleDownloadAsync(download, true);
                comic.Cover = appx;
            }
            catch
            {
            }
        }

        private async static Task HandleDownloadAsync(DownloadOperation download, bool start)
        {
            try
            {
                actives.Add(download);
                Progress<DownloadOperation> callback = new Progress<DownloadOperation>(DownloadProgress);

                if (start)
                {
                    await download.StartAsync().AsTask(callback);
                }
                else
                {
                    await download.AttachAsync().AsTask(callback);
                }
            }
            finally
            {
                actives.Remove(download);
            }
        }

        public async static Task DiscoverActiveDownloadsAsync()
        {
            var downloads = await BackgroundDownloader.GetCurrentDownloadsAsync();
            if (downloads.Count > 0)
            {
                foreach (DownloadOperation download in downloads)
                {
                    if (download.ResultFile.Path.Contains("cover"))
                    {       
                        // 此处使用await 会造成图片 无法并发下载
                        HandleDownloadAsync(download, false);
                    }
                }
            }
        }

        private static void DownloadProgress(DownloadOperation download)
        {
            //try
            //{
            //    using (DbContext context = new DbContext())
            //    {
            //        if (download.Progress.Status == BackgroundTransferStatus.Completed)
            //        {
            //            var name = Path.GetFileNameWithoutExtension(download.ResultFile.Name);
            //            int id;
            //            if (int.TryParse(name, out id))
            //            {
            //                var comic = await context.GetAsync<SQLiteComic>(id);
            //                comic.CoverPath = download.ResultFile.Name;
            //                await context.UpdateAsync(comic);
            //            }
            //        }
            //    }
            //}
            //catch(Exception ex)
            //{
            //    if (ex.Message != null)
            //    { 
            //    }
            //}
        }
    }
}
